package com.meirengu.webview.controller;

import com.meirengu.common.RedisClient;
import com.meirengu.model.Result;
import com.meirengu.utils.*;
import com.meirengu.webview.service.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.meirengu.common.StatusCode.*;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;


/**
 * ${DESCRIPTION}
 *
 * @author Mao
 * @create 2017-05-24 15:58
 */
@Controller
@RequestMapping("information")
public class InformationController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(InformationController.class);

    @Autowired
    InformationService informationService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    UserService userService;

    @Autowired
    KwUserChannelService kwUserChannelService;

    @Autowired
    KwProductService kwProductService;

    @Autowired
    private LmUserBaseService lmUserBaseService;

    @Autowired
    RedisClient redisClient;

    /**
     * 注册页1
     *
     * @return
     */
    @RequestMapping(value = "signUp", method = GET)
    public String SignUp() {
        return "information/signUp";
    }

    /**
     * 注册页2
     *
     * @return
     */
    @RequestMapping(value = "signUp2", method = GET)
    public String SignUp2(@RequestParam(required = true) String phone, ModelMap model) {
        logger.debug("phone:" + phone);
        model.addAttribute("phone", phone);
        return "information/signUp2";
    }

    /**
     * 查看服务协议
     *
     * @return
     */
    @RequestMapping(value = "userNotes", method = GET)
    public String UserNotes() {
        return "information/userNotes";
    }

    /**
     * 用户手机注册
     *
     * @param phone
     * @param cid
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addMobile", method = POST)
    public Result addMobile(HttpServletRequest request,
                            @RequestParam(value = "phone", required = false) String phone,
                            @RequestParam(value = "cid", required = false) String cid,
                            @RequestParam(value = "money", required = false) String money) {
        try {
            logger.info("addMobile phone:" + phone + " cid:" + cid + " money: " + money);
            //verify params
            if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(money)) {
                return super.setResult(MISSING_ARGUMENT, null, codeMsgMap.get(MISSING_ARGUMENT));
            }
            if (!ValidatorUtil.isMobile(phone)) {
                return super.setResult(MOBILE_FORMAT_ERROR, null, codeMsgMap.get(MOBILE_FORMAT_ERROR));
            }
            //判断用户是否已经存在
            boolean flag = informationService.isExist(phone);
            if (flag) {
                return super.setResult(USER_IS_EXITS, "", codeMsgMap.get(USER_IS_EXITS));
            }
            String ip = RequestUtil.getClientIp(request);
            if (StringUtils.isNotBlank(cid) && cid.contains("#")) {
                int endIndex = cid.indexOf("#");
                cid = cid.substring(0, endIndex);
            }
            Integer updateFlag = informationService.signUp(phone, cid, ip, money);
            if (updateFlag == 1) {
                redisClient.sadd("kwdRegister", phone);
                return super.setResult(OK, "", codeMsgMap.get(OK));
            } else {
                logger.error("用户表插入失败");
                return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
            }
        } catch (Exception e) {
            e.printStackTrace();
            String param = String.format("参数：phone:%s,cId:%s,money:%s", phone,
                    cid, money);
            logger.error(">> InformationController.addMobile throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), param);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }
    }

    /**
     * 添加新手机号，无期望金额
     */
    @ResponseBody
    @RequestMapping(value = "addMobileNoMoney", method = POST)
    public Result addMobile(HttpServletRequest request,
                            @RequestParam(value = "phone", required = false) String phone,
                            @RequestParam(value = "cid", required = false) String cid) {
        try {
            logger.info("/addMobileNoMoney request params,phone:" + phone + ",cid:" + cid);
            //verify params
            if (StringUtil.isEmpty(phone)) {
                return super.setResult(MISSING_ARGUMENT, null, codeMsgMap.get(MISSING_ARGUMENT));
            }
            if (!ValidatorUtil.isMobile(phone)) {
                return super.setResult(MOBILE_FORMAT_ERROR, null, codeMsgMap.get(MOBILE_FORMAT_ERROR));
            }
            //判断用户是否已经存在
            boolean flag = informationService.isExist(phone);
            if (flag) {
                return super.setResult(USER_IS_EXITS, "", codeMsgMap.get(USER_IS_EXITS));
            }
            String ip = RequestUtil.getClientIp(request);
            if (StringUtils.isNotBlank(cid) && cid.contains("#")) {
                int endIndex = cid.indexOf("#");
                cid = cid.substring(0, endIndex);
            }
            Integer updateFlag = informationService.signUp(phone, cid, ip);
            if (updateFlag == 1) {
                redisClient.sadd("kwdRegister", phone);
                return super.setResult(OK, "", codeMsgMap.get(OK));
            } else {
                logger.error("用户表插入失败");
                return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
            }
        } catch (Exception e) {
            e.printStackTrace();
            String param = String.format("参数：phone:%s,cId:%s", phone, cid);
            logger.error(">> InformationController.addMobile throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), param);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }
    }

    /**
     * 判断用户是否需要发送短信
     * true 需要发送
     * false 无需发送
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "needSms", method = POST)
    public Result needSms(@RequestParam(value = "mobile", required = true) String mobile,
                          @RequestParam(value = "money", required = true) BigDecimal money) {
        if (StringUtil.isEmpty(mobile) || NumberUtil.isNullOrZero(money)) {
            return super.setResult(MISSING_ARGUMENT, null, codeMsgMap.get(MISSING_ARGUMENT));
        }
        boolean flag = false;
        try {
            flag = informationService.needSms(mobile, money);
            return super.setResult(OK, flag, codeMsgMap.get(OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:mobile:%s", mobile);
            logger.error(">> InformationController.is_exist throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }

    }

    /**
     * 判断用户是否需要发送短信，不需要填写金额
     */
    @ResponseBody
    @RequestMapping(value = "needSmsNoMoney", method = POST)
    public Result needSms(@RequestParam(value = "mobile") String mobile) {
        logger.info("/needSmsNoMoney request params,mobile:{}", mobile);
        if (isEmpty(mobile)) {
            return super.setResult(MISSING_ARGUMENT, null, codeMsgMap.get(MISSING_ARGUMENT));
        }

        try {
            boolean flag = informationService.needSms(mobile);
            return super.setResult(OK, flag, codeMsgMap.get(OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:mobile:%s", mobile);
            logger.error(">> InformationController.is_exist throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }

    }

    /**
     * 查询该用户是否注册
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "is_exist", method = POST)
    public Result isExist(@RequestParam(value = "mobile", required = true) String mobile) {
        boolean flag = false;
        try {
            flag = informationService.isExist(mobile);
            if (flag) {
                return super.setResult(USER_IS_EXITS, null, codeMsgMap.get(USER_IS_EXITS));
            }
            return super.setResult(OK, "", codeMsgMap.get(OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:mobile:%s", mobile);
            logger.error(">> InformationController.is_exist throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }

    }


    @ResponseBody
    @RequestMapping(value = "complement", method = POST)
    public Result Complement(HttpServletRequest request,
                             @RequestParam(value = "phone", required = false) String phone,
                             @RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "sex", required = false) String sex,
                             @RequestParam(value = "city", required = false) String city,
                             @RequestParam(value = "areaCode", required = false) String areaCode,
                             @RequestParam(value = "areaName", required = false) String areaName,
                             @RequestParam(value = "profession", required = false) String profession,
                             @RequestParam(value = "socialSecurity", required = false) String socialSecurity,
                             @RequestParam(value = "housingFund", required = false) String housingFund,
                             @RequestParam(value = "birthday", required = false) String birthday,
                             @RequestParam(value = "income", required = false) String income,
                             @RequestParam(value = "insurance", required = false) String insurance,
                             @RequestParam(value = "housingType", required = false) String housingType,
                             @RequestParam(value = "hasCars", required = false) String hasCars,
                             @RequestParam(value = "creditSituation", required = false) String creditSituation,
                             @RequestParam(value = "paytype", required = false) String paytype,
                             @RequestParam(value = "worklong", required = false) String worklong,
                             @RequestParam(value = "acceptsafety", required = false) String acceptsafety,
                             @RequestParam(value = "lifeInsurance", required = false) String lifeInsurance,
                             @RequestParam(value = "isAtom", required = false) String isAtom,
                             @RequestParam(value = "enpass", required = false, defaultValue = "1") String enpass,
                             @RequestParam(value = "idcard", required = false) String idcard) {
        try {
            logger.debug("params: phone:" + phone + " name:" + name + " sex:" + sex + " city：" + city
                    + " areaCode：" + areaCode + " areaName：" + areaName + " profession：" + profession
                    + " socialSecurity：" + socialSecurity + " housingFund:" + housingFund + " birthday:" + birthday
                    + " income:" + income + " insurance:" + insurance + " housingType:" + housingType + " hasCars:" + hasCars
                    + " creditSituation" + creditSituation + " paytype:" + paytype + " worklong:" + worklong
                    + " acceptsafety:" + acceptsafety + " lifeInsurance:" + lifeInsurance + " isAtom:" + isAtom + " enpass:" + enpass + isAtom + " idcard:" + idcard);
            //verify params
            if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(name) ||
                    StringUtil.isEmpty(sex) || StringUtil.isEmpty(city) ||
                    StringUtil.isEmpty(areaName) || StringUtil.isEmpty(profession) || StringUtil.isEmpty(socialSecurity) ||
                    StringUtil.isEmpty(housingFund) || StringUtil.isEmpty(birthday) || StringUtil.isEmpty(income) ||
                    StringUtil.isEmpty(insurance) || StringUtil.isEmpty(housingType) || StringUtil.isEmpty(hasCars) ||
                    StringUtil.isEmpty(creditSituation) || StringUtil.isEmpty(paytype) || StringUtil.isEmpty(worklong) ||
                    StringUtil.isEmpty(acceptsafety) || StringUtil.isEmpty(lifeInsurance) || StringUtil.isEmpty(isAtom) ||
                    StringUtil.isEmpty(enpass)) {
                return super.setResult(MISSING_ARGUMENT, null, codeMsgMap.get(MISSING_ARGUMENT));
            }
            name = URLDecoder.decode(name, "utf-8");
            name = StringUtil.filterEmoji(name).trim();
            areaName = (URLDecoder.decode(areaName, "utf-8")).trim();
            city = (URLDecoder.decode(city, "utf-8")).trim();
            if (!ValidatorUtil.isMobile(phone)) {
                return super.setResult(MOBILE_FORMAT_ERROR, null, codeMsgMap.get(MOBILE_FORMAT_ERROR));
            }
            String userAgent = request.getHeader("user-agent");
            String ip = RequestUtil.getClientIp(request);
            boolean flag = informationService.isExist(phone);
            if (!flag) {
                logger.error("用户不存在");
                return super.setResult(USER_NOT_EXITS, "", codeMsgMap.get(USER_NOT_EXITS));
            }
            Integer _sex = StringUtil.getIntValue(sex);
            Integer updateFlag = informationService.updateUser(phone, name, _sex, city, birthday, userAgent);
            if (updateFlag != 1) {
                //return super.setResult(OK, "", codeMsgMap.get(OK));
                logger.error("用户表更新失败");
                return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
            }
            informationService.complement(phone, name, sex, city, areaCode, areaName, profession
                    , socialSecurity, housingFund, birthday
                    , income, insurance, housingType, hasCars
                    , creditSituation, paytype, worklong
                    , acceptsafety, lifeInsurance, isAtom, enpass, ip, idcard);
            return super.setResult(OK, "", codeMsgMap.get(OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:phone:%s, name:%s, sex:%s, city:%s, areaCode:%s, areaName:%s, profession:%s," +
                            " socialSecurity:%s, housingFund:%s, birthday:%s,income:%s, insurance:%s, housingType:%s, hasCars:%s,creditSituation:%s, paytype:%s, worklong:%s" +
                            " acceptsafety:%s, lifeInsurance:%s, isAtom:%s, enpass:%s, ip:%s, idcard:%s", phone, name, sex, city, areaCode, areaName, profession,
                    socialSecurity, housingFund, birthday, income, insurance, housingType, hasCars,
                    creditSituation, paytype, worklong, acceptsafety, lifeInsurance, isAtom, enpass, RequestUtil.getClientIp(request), idcard);
            logger.error(">> InformationController.complement throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }

    }

    @ResponseBody
    @RequestMapping(value = "loanMarket", method = POST)
    public Result loanMarket(@RequestParam(value = "mobile", required = false) String mobile) {
        try {
            //mobile 参数暂时不用

            //get loan list
            Map<String, Object> params = new HashMap<>();
            params.put("status", 1);
            List<Map<String, Object>> channellist = kwProductService.getList(params);
            if (channellist != null && channellist.size() > 0) {
                for (int i = 0; i < channellist.size(); i++) {
                    Map<String, Object> map = channellist.get(i);
                    Random random = new Random();
                    int baseNum = 0;
                    int increateNum = 0;
                    int maxAmount = 0;
                    if (map.containsKey("maxAmount")) {
                        baseNum = StringUtil.getIntValue(map.get("maxAmount").toString());
                    }
                    if (map.containsKey("recommendMonRate") && map.get("recommendMonRate") != null) {
                        increateNum = (int) StringUtil.getDoubleValue(map.get("recommendMonRate").toString());
                    }
                    int diff = (int) DateUtils.getDaySub(map.get("createDate").toString(), DateUtils.getNowTimestamp().toString());
                    int round = random.nextInt(1000);
                    maxAmount = baseNum + diff * increateNum + round;
                    //logger.debug("baseNum:"+baseNum+" increateNum:"+increateNum+"maxAmount:"+maxAmount);
                    map.replace("maxAmount", maxAmount);
                }
            }

            return super.setResult(OK, channellist, codeMsgMap.get(OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:mobile:%s", mobile);
            logger.error(">> InformationController.loanMarket throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(INTERNAL_SERVER_ERROR, "", codeMsgMap.get(INTERNAL_SERVER_ERROR));
        }
    }


}
